# -*- coding: utf-8 -*-
# !/usr/bin/env python
import subprocess
from utils.mysql_utils import query_to_list, sql_decrypt
import logging

from utils.views import ReturnClass

logger = logging.getLogger('django')

class GitClass():
    def __init__(self):
        self.sys_other_privilege_data = query_to_list('SELECT * FROM sys_other_privilege a  WHERE a.sys_other_privilege_flag = "git"', None, True)

    def exec_local_cmd(self, command, cwd):
        ret = subprocess.run(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8",
                             timeout=600,cwd=cwd)
        if ret.returncode == 0:
            logger.info("success: %s" %ret.stdout)
        else:
            logger.error("error: %s" %(ret.stdout + ret.stderr))

        self.exec_local_cmd_returncode = ret.returncode

        return (ret.stdout)

    def clone(self, address, branch, path):
        #cmd = "git clone -b develop https://18186496302:Wangwuli123\!@gitee.com/easylinkin/web-deploy.git"

        https_userpass_url = "https://{sys_other_privilege_user}:{sys_other_privilege_pass}@".format(
            sys_other_privilege_user=self.sys_other_privilege_data['sys_other_privilege_user'],
            sys_other_privilege_pass=sql_decrypt(self.sys_other_privilege_data['sys_other_privilege_pass'])
        )
        address = address.replace("https://",https_userpass_url )

        cmd = "git clone -b {branch} {address} {path}".format(branch=branch,address=address,path=path)

        cmd_re_data = self.exec_local_cmd(cmd, path)
        if self.exec_local_cmd_returncode:
            return ReturnClass.return_bust('克隆项目仓库失败：%s' %cmd_re_data)

        return ReturnClass.return_succeed('克隆项目成功')

    def pull(self, branch, cwd):
        cmd_re_data = self.exec_local_cmd("git checkout %s" %branch, cwd)
        if self.exec_local_cmd_returncode:
            return ReturnClass.return_bust('切换分支失败：%s' %cmd_re_data)
        cmd_re_data = self.exec_local_cmd("git pull", cwd)
        if self.exec_local_cmd_returncode:
            return ReturnClass.return_bust('拉取代码失败：%s' %cmd_re_data)

        return ReturnClass.return_succeed('拉取项目成功')

    def push(self):
        pass

